// pages/publish/publish.js
const util = require('../../utils/util.js')

Page({
  data: {
    content: '',
    images: []
  },

  // 输入内容变化
  onContentChange(e) {
    const content = e.detail.value.slice(0, 500)
    this.setData({ content })
  },

  // 选择图片
  chooseImage() {
    wx.chooseImage({
      count: 9 - this.data.images.length,
      sizeType: ['compressed'],
      success: res => {
        this.setData({
          images: this.data.images.concat(res.tempFilePaths)
        })
      }
    })
  },

  // 删除图片
  removeImage(e) {
    const index = e.currentTarget.dataset.index
    const images = this.data.images
    images.splice(index, 1)
    this.setData({ images })
  },

  // 提交动态
  submitPost() {
    const { content, images } = this.data
    
    if (!content.trim() && images.length === 0) {
      wx.showToast({ title: '内容不能为空', icon: 'none' })
      return
    }

    // 获取前页实例
    const pages = getCurrentPages()
    const indexPage = pages[pages.length - 2]
    
    // 生成新动态
    const newPost = {
      id: Date.now(),
      user: {
        name: "我",
        avatar: "/images/my-avatar.jpg"
      },
      content: content,
      images: images,
      time: util.formatTime(new Date()),
      likes: 0,
      isLiked: false,
      comments: []
    }

    // 更新首页数据
    indexPage.data.postList.unshift(newPost)
    indexPage.setData({ postList: indexPage.data.postList })
    
    // 返回并显示成功提示
    wx.navigateBack()
    wx.showToast({ title: '发布成功' })
  }
})